package cyclequeue;
//使用 flg 标记，判断队列是否已满
public class MyQueue3 {
    private  int[] elem;
    private int front;
    private int rear;
    private boolean flg;
    public MyQueue3(int k) {
        this.elem = new int[k];
        this.front = 0;
        this.rear = 0;
        this.flg = true;
    }
    public boolean offer(int val) {
        if(isFull()) {
            return false;
        }

        elem[rear] = val;
        rear = (rear + 1) % elem.length;
        flg = true;
        return true;
    }

    public boolean poll() {
        if(isEmpty()) {
            return false;
        }
        front = (front + 1) % elem.length;
        flg = false;
        return true;
    }

    public int peekFront() {
        if(isEmpty()) {
            throw new QueueIsFull("空队列");
        }
        return elem[front];
    }

    public int peekRear() {
        if(isEmpty()) {
            throw new QueueIsFull("空队列");
        }
        return rear == 0 ? elem[elem.length-1] : elem[rear-1];
    }

    public boolean isEmpty() {
        return rear == front && !flg;
    }

    public boolean isFull() {
        return rear == front && flg;
    }
}
